//
//  SpringBoardViewViewController.m
//  SpringBoardView
//
//  Created by Kishikawa Katsumi on 10/01/24.
//  Copyright Kishikawa Katsumi 2010. All rights reserved.
//

#import "SpringBoardViewController.h"
#import "SpringBoardViewButton.h"

#define NUMBER_OF_BUTTONS 10

@implementation SpringBoardViewController

@synthesize isEditing;

- (void)loadView {
    UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 20.0f, 320.0f, 460.0f)];
    contentView.backgroundColor = [UIColor blackColor];
    self.view = contentView;
    [contentView release];
    
    UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 44.0f)];
    navBar.barStyle = UIBarStyleBlack;
    [contentView addSubview:navBar];
    [navBar release];
    
    navItem = [[UINavigationItem alloc] initWithTitle:@"SpringBoard Demo"];
    navBar.items = [NSArray arrayWithObject:navItem];
    [navItem release];
    
    UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0.0f, 416.0f, 320.0f, 44.0f)];
    toolbar.barStyle = UIBarStyleBlack;
    [contentView addSubview:toolbar];
    [toolbar release];
    
    buttons = [[NSMutableArray alloc] initWithCapacity:20];
	for (int i = 0; i < NUMBER_OF_BUTTONS; i++) {
        SpringBoardViewButton *button = [[SpringBoardViewButton alloc] init];
        [button setExclusiveTouch:YES];
        button.frame = CGRectMake(4.0f + (80.0f * (i % 4)), 8.0f + (86.0f * (i / 4)) + 44.0f, 75.0f, 75.0f);
        button.controller = self;
        [contentView addSubview:button];
        [button release];
        
        [buttons addObject:button];
	}
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(beginEditing:)
                                                 name:SpringBoardViewBeginEditingNotification object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(buttonLayoutChanging:)
												 name:SpringBoardViewButtonLayoutChangingNotification object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(buttonLayoutChanged:)
												 name:SpringBoardViewButtonLayoutChangedNotification object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)dealloc {
    [super dealloc];
}

- (void)beginEditing:(NSNotification *)notification {
	isEditing = YES;
    
    UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone 
                                                                                target:self
                                                                                action:@selector(endEditing:)];
    [navItem setRightBarButtonItem:doneButton animated:YES];
    [doneButton release];
    
	[buttons makeObjectsPerformSelector:@selector(setEditingWithNumber:) withObject:[NSNumber numberWithBool:YES]];
}

- (void)endEditing:(id)sender {
	isEditing = NO;
    
    [navItem setRightBarButtonItem:nil animated:YES];
    
	[buttons makeObjectsPerformSelector:@selector(setEditingWithNumber:) withObject:[NSNumber numberWithBool:NO]];
}

+ (NSUInteger)buttonIndexFromCGRect:(CGRect)rect {
	NSUInteger x = (rect.origin.x - 4.0f) / 80.0f;
	NSUInteger y = (rect.origin.y - 8.0f) / 86.0f;
	return 4 * y + x;
}

+ (CGRect)buttonFrameFromIndex:(NSUInteger)index {
	CGRect frame;
	frame.origin.x = 4.0f + 80.0f * (index % 4);
	frame.origin.y = 8.0f + 86.0f * (index / 4) + 44.0f;
	frame.size.width = 75.0f;
	frame.size.height = 75.0f;
	return frame;
}

- (CGRect)lastItemPosition {
	return [SpringBoardViewController buttonFrameFromIndex:[buttons count] - 1];
}

- (void)reorderButtons {
	LOG_CURRENT_METHOD;
	
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:0.15f];
	
	for (int i = 0;  i < [buttons count]; i++) {
		SpringBoardViewButton *button = [buttons objectAtIndex:i];
		if (button.isDragging) {
			continue;
		}
		CGRect frame = [SpringBoardViewController buttonFrameFromIndex:i];
		button.frame = frame;
	}
	[UIView commitAnimations];
}

- (void)moveButtonfromIndex:(NSUInteger)fromIndex toIndex:(NSUInteger)toIndex {
	if (fromIndex >= [buttons count]) {
		return;
	}
	if (toIndex >= [buttons count]) {
		toIndex = [buttons count] - 1;
	}
	
	SpringBoardViewButton *movingButton = [buttons objectAtIndex:fromIndex];
	[[buttons retain] autorelease];
	
	[buttons removeObjectAtIndex:fromIndex];
    [buttons insertObject:movingButton atIndex:toIndex];
}

- (void)buttonLayoutChanging:(NSNotification *)notification {
	LOG_CURRENT_METHOD;
    NSDictionary *userInfo = [notification userInfo];
    CGRect fromRect = [[userInfo objectForKey:@"fromRect"] CGRectValue];
    CGRect toRect = [[userInfo objectForKey:@"toRect"] CGRectValue];
	
	NSUInteger fromIndex = [SpringBoardViewController buttonIndexFromCGRect:fromRect];
	NSUInteger toIndex = [SpringBoardViewController buttonIndexFromCGRect:toRect];
	
	[self moveButtonfromIndex:fromIndex toIndex:toIndex];
    
	[self reorderButtons];
}

- (void)buttonLayoutChanged:(NSNotification *)notification {
	LOG_CURRENT_METHOD;
    NSDictionary * userInfo = [notification userInfo];
    CGRect fromRect = [[userInfo objectForKey:@"fromRect"] CGRectValue];
    CGRect toRect = [[userInfo objectForKey:@"toRect"] CGRectValue];
	LOG(@"fromRect = %@, toRect = %@", NSStringFromCGRect(fromRect), NSStringFromCGRect(toRect));
	
	NSUInteger fromIndex = [SpringBoardViewController buttonIndexFromCGRect:fromRect];
	NSUInteger toIndex = [SpringBoardViewController buttonIndexFromCGRect:toRect];
	
	[self moveButtonfromIndex:fromIndex toIndex:toIndex];
	
	[self reorderButtons];
}

@end
